/*
 * Copyright (c) 2017 zhangcm. All Rights Reserved.
 */
package com.jnzc.ocr.rest.app.shop.task;

import com.jnzc.ocr.common.utils.ArrayHandleUtils;
import com.jnzc.ocr.serv.shop.api.ShopGoodsApi;
import com.jnzc.ocr.serv.shop.api.ShopMainApi;
import com.jnzc.ocr.serv.shop.api.ShopProductApi;
import com.jnzc.ocr.serv.shop.entity.ShopGoods;
import com.jnzc.ocr.serv.shop.entity.ShopMain;
import com.jnzc.ocr.serv.system.api.SysCompanyApi;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhangcm
 * @version 1.0, 2017/11/26
 */
@Component
public class ShopStockWarnTask {

    private static final Logger logger = LoggerFactory.getLogger(ShopStockWarnTask.class);

    @Autowired
    private SysCompanyApi sysCompanyApi;

    @Autowired
    private ShopMainApi shopMainApi;

    @Autowired
    private ShopGoodsApi shopGoodsApi;

    @Autowired
    private ShopProductApi shopProductApi;

    @Scheduled(cron = "0 5 1 * * ?")
    public void exec() {
        List<Long> companyIdList = sysCompanyApi.listId();
        logger.info("companyIdList.size: {}", companyIdList.size());
        for (Long companyId : companyIdList) {
            List<ShopMain> shopList = shopMainApi.listByCompanyId(companyId);
            for (ShopMain shop : shopList) {
                try {
                    exec(shop);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    private void exec(ShopMain shop) {
        if(null == shop.getWarnStockNum()) {
            return;
        }
        shopProductApi.clearLowStock(shop.getId());
        List<ShopGoods> goodList = shopGoodsApi.listWarn(shop.getWarnStockNum(), shop.getId());
        if(CollectionUtils.isEmpty(goodList)) {
            return;
        }
        List<Long> productIdList = ArrayHandleUtils.readAttrList(goodList, "id");
        shopProductApi.updateLowStock(productIdList, shop.getId());
    }
}
